//
//  GYDTabBar.swift
//  Weibo
//
//  Created by 贵永冬 on 16/7/15.
//  Copyright © 2016年 贵永冬. All rights reserved.
//

import UIKit

class GYDTabBar: UITabBar {

    /// 发布按钮点击回调
    var addButtonBlock : (() -> Void)?
    
    /**
     重写父类的布局方法
     */
    override func layoutSubviews() {
        super.layoutSubviews()
        var i = 0
        for item in self.subviews {
            if item.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                self.layoutButtonItemWithButton(item, index: i)
                if i == 1 {
                    i += 1
                }
                i += 1
            }
        }
    }
    /**
     布局buttonItem
     
     - parameter button: buttonItem
     - parameter index:  索引
     */
    private func layoutButtonItemWithButton(item: UIView, index: Int) {
        let width : CGFloat = GYDWindowWidth / 5.0
        let height : CGFloat = 49
        item.frame = CGRect(x: (CGFloat(index))*width, y: 0, width: width, height: height)
       
        if index == 1 {
            let addButton = self.createAddButton(CGRect(x: 2.0*width, y: 0, width: width, height: height))
            addButton.addTarget(self, action:#selector(GYDTabBar.addButtonClick) , forControlEvents: UIControlEvents.TouchUpInside)
            self.addSubview(addButton)
        }
    }
    /**
     加号发布按钮点击
     */
    @objc private func addButtonClick() {
        if let tempBlock = self.addButtonBlock {
            tempBlock()
        }
    }
    
    
    private func createAddButton(frame:CGRect) -> UIButton {
        let addButton = UIButton(type: UIButtonType.Custom)
        addButton.frame = frame
        addButton.setImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        addButton.setImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        let addImageView = UIImageView(image:UIImage(named: "tabbar_compose_icon_add"))
        addImageView.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
        addImageView.center = CGPoint(x: frame.size.width/2.0, y: frame.size.height/2.0)
        addButton.addSubview(addImageView)
        return addButton
    }
    
    
}
